package com.aboverock.core.spring.web;

import com.aboverock.common.domain.Result;
import com.aboverock.common.enums.MessageSourceKey;
import com.aboverock.core.orm.domain.BaseEntity;
import com.baomidou.mybatisplus.extension.service.IService;
import io.swagger.annotations.ApiOperation;
import javax.validation.Valid;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;

public abstract class StringIdBaseController<T extends BaseEntity<String>> extends BaseController<T, IService<T>> {
    
    /**
     * 通过id获取数据.
     *
     * @param id the id
     * @return the by id
     */
    @ApiOperation(value = "根据id获取数据信息")
    @GetMapping("{id}")
    public Result getById(@PathVariable("id") String id) {
        T entity = baseService.getById(id);
        return Result.success(entity);
    }

    /**
     * 根据id更新数据.
     *
     * @param id the id
     * @param entity the entity
     * @return the result
     */
    @ApiOperation(value = "根据id更新数据信息")
    @PutMapping("{id}")
    public Result update(@PathVariable("id") String id, @Valid @RequestBody T entity) {
        T oldEntity = baseService.getById(id);
        if (null == oldEntity) {
            return Result.fail(MessageSourceKey.Common.COMMON_DATA_NOT_FOUND_KEY);
        }

        entity.setId(id);
        if (baseService.updateById(entity)) {
            return Result.success(entity);
        }
        return Result.fail();
    }

    /**
     * Delete.
     *
     * @param id the id
     * @return the result
     */
    @ApiOperation(value = "根据id删除数据信息")
    @DeleteMapping("{id}")
    public Result delete(@PathVariable("id") String id) {
        if (baseService.removeById(id)) {
            return Result.success();
        }
        return Result.fail();
    }

}
